package com.jpa.service.impl;

import com.jpa.anno.DS;
import com.jpa.config.DynamicDataSourceContextHolder;
import com.jpa.entity.dy.User;
import com.jpa.repository.dy.UserRepository;
import com.jpa.service.SignUserService;
import com.jpa.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository dyUserRepository;

    @Autowired
    private SignUserService signUserService;

    @DS(value = "db1")
    @Override
    public List<User> findByUserName(String userName) {
        return dyUserRepository.findUserByUserName(userName);
    }

    @DS(value = "db2")
    @Override
    public List<User> findByUserNameDb2(String userName) {
        return dyUserRepository.findUserByUserName(userName);
    }

//    @DS(value = "data_jpa")
    @Override
    public List<User> findAllDb1() {
        DynamicDataSourceContextHolder.setDataSourceType("data_jpa");
        return dyUserRepository.findAll();
    }

//    @DS(value = "test")
    @Override
    public List<User> findAllDb2() {
        DynamicDataSourceContextHolder.setDataSourceType("test");
        return dyUserRepository.findAll();
    }

    @Override
    public void syncUser() {
        List<User> saves = new ArrayList<>();
        List<com.jpa.entity.sign.User> all = signUserService.findAll();
        for (com.jpa.entity.sign.User u : all) {
            User us = new User();
            BeanUtils.copyProperties(u, us);
            System.out.println(us);
            saves.add(us);
        }
        DynamicDataSourceContextHolder.setDataSourceType("test");
        List<User> users = dyUserRepository.saveAll(saves);
        for (User uu : users) {
            System.out.println(uu);
        }
        DynamicDataSourceContextHolder.setDataSourceType("test2");
        List<User> users2 = dyUserRepository.saveAll(saves);
        for (User uu : users2) {
            System.out.println(uu);
        }
    }
}
